package com.ct.websocket3;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 如果你想主动给某个用户推送消息，需要维护一个 Map<String, WebSocketSession>。
 */
public class WebSocketSessionManager {
    private static final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    public static void addSession(String uid, WebSocketSession session) {
        sessions.put(uid, session);
    }

    public static void removeSession(String uid) {
        sessions.remove(uid);
    }

    /**
     * 调用 WebSocketSessionManager.sendMessage("1001", "Hello") 给用户 1001 发送消息！
     * @param uid
     * @param message
     * @throws IOException
     */
    public static void sendMessage(String uid, String message) throws IOException {
        WebSocketSession session = sessions.get(uid);
        if (session != null && session.isOpen()) {
            session.sendMessage(new TextMessage(message));
        }
    }
}